package com.kangfu.api.interceptor;

import cn.hutool.core.util.StrUtil;
import com.kangfu.db.model.bo.wechat.TokenBo;
import com.kangfu.api.service.ITokenService;
import com.kangfu.common.annotation.IgnoreAuth;
import com.kangfu.common.exception.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    public static final Logger logger = LoggerFactory.getLogger(AuthorizationInterceptor.class);

    public static final String LOGIN_TOKEN_KEY = "X-KANNGFU-TOKEN";
    public static final String LOGIN_USER_ID = "LOGIN_USER_ID";

    @Autowired
    public ITokenService tokenService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        IgnoreAuth annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        } else {
            return true;
        }
        //如果有@IgnoreAuth注解，则不验证token
        if (annotation != null) {
            return true;
        }
        //从header中获取token
        String token = request.getHeader(LOGIN_TOKEN_KEY);
        //如果header中不存在token，则从参数中获取token
        if (StrUtil.isBlank(token)) {
            token = request.getParameter(LOGIN_TOKEN_KEY);
        }
        //token为空
        if (StrUtil.isBlank(token)) {
            System.out.println(request.getRequestURI());
            throw new AuthorizationException("token不能为空");
        }
        System.out.println("token:" + token);

        //校验token
        TokenBo tokenBo = tokenService.verifyToken(token);

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(LOGIN_USER_ID, tokenBo.getUserId());
        request.setAttribute(LOGIN_TOKEN_KEY, token);
        return true;
    }

}
